<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use OSS\OssClient;
/**
 * 设计页面
 *
 * @icon fa fa-circle-o
 */
class DesignPages extends Backend
{

    /**
     * DesignPages模型对象
     * @var \app\admin\model\deerhome\DesignPages
     */
    protected $model = null;
    protected $searchFields = 'page_title';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\DesignPages;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("cateList", $this->model->getCateList());
        $this->view->assign("canDelList", $this->model->getCanDelList());
    }

    public function preview(){
        $id=$this->request->param('id','','intval');
        $data=Db::name("deerhome_design_pages")->where("id",$id)->find();
        if(!$data){
            $this->error("页面不存在");
        }
        $out=[];
        $out['qr']=$data['qr_preview'];
        if(!$out['qr']){
            $out['qr']=$this->creatQrcode($this->auth->id,$id);
        }
        $this->success('',null,$out);
    }
    public function design_save(){
        $online=$this->request->param('online',0,'intval');
        $id=$this->request->param('id',0,'intval');
        $com=$this->request->param('com','[]','trim');
        $setup=$this->request->param('setup','[]','trim');
        $data=Db::name("deerhome_design_pages")->where("id",$id)->find();
        if(!$data){
            $this->error("页面不存在");
        }
        $con=[];
        $con['com']=json_decode($com,true);
        $con['setup']=json_decode($setup,true);
        $edit=[];
        $edit['con_preview']=json_encode($con,JSON_UNESCAPED_UNICODE);
        if($online==1){
            $edit['status']=1;
            $edit['con']=$edit['con_preview'];
            $edit['update_time']=date("Y-m-d H:i:s");
        }
        if(strlen($edit['con_preview'])>65535){
            $this->error("数据过大，请精简页面组件");
        }
        Db::startTrans();
        try{
            Db::name("deerhome_design_pages")->where("id",$id)->update($edit);
            if($online==1 && $data['cate']==1){
                Db::name("deerhome_design_pages")->where('cate',$data['cate'])->where("id","<>",$id)->update(['status'=>2]);
            }
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }

    public function del($ids = null){
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $data=$this->model->where('id',$ids)->find();
        if(!$data){
            $this->error("页面不存在");
        }
        if($data['can_del']==2){
            $this->error("系统页面不可删除");
        }
        $this->model->destroy($ids);
        $this->success();
    }

    /**
     * 生成小程序码
    */
    private function creatQrcode($saasId,$pageId){
        $fileName="page-{$saasId}-{$pageId}.png";
        $filePath= APP_PATH ."../public/uploads/".$fileName;
        $imgUrl="qr/{$fileName}";
        $img="";
        try{
            $data=Db::name("deerhome_xcxpz")->where("platform","xcx_config")->find();
            if(!$data){
                throw new \Exception("没有配置信息");
            }
            $configWx=\json_decode($data['con'],true);
            $Qrcode = \WeMini\Qrcode::instance($configWx);
            $query="/pages/design?p=1&id={$pageId}";
            $img = $Qrcode->createMiniPath($query);
            file_put_contents($filePath,$img);
        }catch(\Exception $e){
            $this->error($e->getMessage());
        }
        $config = get_addon_config('alioss');
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
        try {
            $oss->uploadFile($config['bucket'], $imgUrl, $filePath);
        } catch (\Exception $e) {
            $this->error("上传失败".$e->getMessage());
        }
        if(file_exists($filePath)){
            unlink($filePath);
        }
        $cdnurl=cdnurl("/".$imgUrl, true);
        Db::name("deerhome_design_pages")->where("id",$pageId)->update(['qr_preview'=>$cdnurl]);
        return $cdnurl;
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
